import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import json
import time
import random
import datetime
import requests
from requests.exceptions import ConnectionError
from xhsapi import XhsApi
import redis
import re
import config
from adsl import ADSL





class XhsRegister(object):
    def __init__(self, cid):
        adsl_obj = ADSL()
        adsl_obj.reconnect()
        self.cid = cid
        self.xhsapi = None
        self.init_devices()

        # self.init_devices()

    def init_xhsapi(self):
        self.xhsapi = XhsApi(self.cid)


    # 休息随机秒
    def sleep_random(self, t1=0, t2=0):
        if t1 > 0 and t2 > 0:
            sleep_time = random.random() + random.randint(t1, t2)
        elif t1 > 0:
            sleep_time = t1
        else:
            sleep_time = random.random() + random.randint(1, 2)
        print(str(datetime.datetime.now()) + "   休息随机秒 %s" % sleep_time)
        time.sleep(sleep_time)

    # 初始化设备
    def init_devices(self):
        self.xhs_login()
        # with open('user.txt', 'r', encoding="utf8") as f:
        #     for line in f:
        #         username, password = line.strip().split('----')
        #         self.xhs_login(username, password)
        #         break
    # 获取手机号
    def get_phonenum(self):
        redis_obj = redis.StrictRedis(
            host=config.redisServer,
            port=1111,
            db=13,
            decode_responses=True,
            password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
        )

        while True:
            phonenum = redis_obj.rpop("XHS::XIANSUO::LIST::PHONENUM")
            if phonenum:

                return phonenum
            else:
                redis_obj.lpush("XHS::XIANSUO::LIST::PHONENUM::SIGNAL", 1)
                print("无可用手机号,发送信号获取")
                time.sleep(5)

    def get_code(self, phonenum):

        redis_obj = redis.StrictRedis(
            host=config.redisServer,
            port=1111,
            db=13,
            decode_responses=True,
            password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
        )
        redis_key = "XHS::XIANSUO::HASH::PHONENUM"
        redis_obj.hset(redis_key, phonenum, time.time())

        redis_key = "XHS::XIANSUO::KEY::PHONENUM::{phonenum}".format(phonenum=phonenum)
        while True:
            code = redis_obj.get(redis_key)
            if code:
                redis_obj.delete(redis_key)
                return code
            else:
                time.sleep(0.5)

    def del_phone_redis_key(self, phone):
        redis_obj = redis.StrictRedis(
            host=config.redisServer,
            port=1111,
            db=13,
            decode_responses=True,
            password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
        )
        redis_key = "XHS::XIANSUO::HASH::PHONENUM"
        redis_obj.hdel(redis_key, phone)

    def lpush_user_ck(self, user_ck):
        redis_obj = redis.StrictRedis(
            host=config.redisServer,
            port=1111,
            db=13,
            decode_responses=True,
            password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
        )
        redis_key = "XHS::XIANSUO::LIST::USER_CK"
        redis_obj.lpush(redis_key, user_ck)
        print("当前可用ck数 -->", redis_obj.llen(redis_key))
        time.sleep(1)

    def xhs_login(self):
        self.init_xhsapi()
        self.xhsapi.init_new_device_params()
        register_smid_ret = self.xhsapi.register_smid()
        print('register_smid_ret:' + register_smid_ret)

        smid = json.loads(register_smid_ret)['detail']['deviceId']
        print('smid:' + smid)
        self.xhsapi.set_smid(smid)

        # 激活用户
        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)
        success = json.loads(active_user_ret)['success']
        if not success:
            crypt_method = json.loads(active_user_ret)['crypt_method']
            print('crypt_method: ' + crypt_method)
            self.xhsapi.set_crypt_method(crypt_method)

        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)

        # if 'data' not in json.loads(active_user_ret):
        #     return False

        # 设置session id
        session_id = ''
        # active_json = json.loads(active_user_ret)
        # if 'data' in active_json:
        #     session_id = active_json['data']['session']
        #     print('session_id:' + session_id)

        # 短信验证码登录
        if len(session_id) == 0:
            # print("需要短信验证,退出")
            # exit()
            # 发送短信验证码
            phone = self.get_phonenum()
            print('phone -->', phone)
            time.sleep(random.randint(3, 8))
            # phone = input("请输入手机号: ")
            send_code_ret = self.xhsapi.send_sms_code(phone)
            print('send_code_ret:' + send_code_ret)
            if not json.loads(send_code_ret)['success']:
                self.del_phone_redis_key(phone)
                return False


            n = 0
            while True:
                print("获取验证码")
                n += 1
                # time.sleep(5)
                sms_code = self.get_code(phone)
                if "您的验证码是" in sms_code:
                    sms_code = sms_code.split(":")[1].split('，')[0].strip()
                    print('sms_code:' + sms_code)
                    break

                if n > 10:
                    print("未获取到验证码,退出")
                    return
            print('sms_code:' + sms_code)

            # 验证短信验证码
            check_code_ret = self.xhsapi.check_sms_code(phone, sms_code)
            print('check_code_ret:' + check_code_ret)

            # 用短信验证码登录
            mobile_token = json.loads(check_code_ret)['data']['token']
            print('mobile_token:' + mobile_token)
            session_id = self.xhsapi.login_with_sms(phone, mobile_token)
            # session_id = "session." + result['session']
            print('session_id:' + session_id)

        # blogger_id = userid
        # blogger_name = result['nickname']
        # blogger_img = result['images']
        # register_time = result['register_time']


        # 设置session_id
        self.xhsapi.set_session_id(session_id)

        # 获取首页推荐
        home_feed = self.xhsapi.get_home_feed()
        print('home_feed -->', home_feed)

        # to_userid = json.loads(home_feed)['data'][0]['user']['userid']
        # print('to_userid -->', to_userid)

        user_data = self.xhsapi.get_register_user_data()
        user_data['phonenumber'] = phone

        # 获取用户信息
        blogger_data = self.xhsapi.get_user_me()
        # print('blogger_data -->', blogger_data)
        blogger_data = json.loads(blogger_data)
        user_data['blogger_data'] = {
            'blogger_id': blogger_data['data']['userid'],
            'blogger_name': blogger_data['data']['nickname'],
            'blogger_img': blogger_data['data']['images'],
        }

        print('user_data -->', user_data)
        self.lpush_user_ck(json.dumps(user_data))
        # with open('register_ok.txt', 'a', encoding="utf8") as f:
        #     f.write(json.dumps(user_data))
        #     f.write("\n")

if __name__ == '__main__':
    cid = "8a23d07c03ba1e59"
    while True:

        try:
            obj = XhsRegister(cid)
        except:
            pass